//
//  TipView.m
//  LotteryClient
//
//  Created by Suny on 14-7-17.
//  Copyright (c) 2014年 CTTC. All rights reserved.
//

#import "TipView.h"
#import <QuartzCore/QuartzCore.h>
#import "UIView+BaseFramework.h"
#import "NSString+BaseFramework.h"

#define kTextTipWidth      200
#define kTextTipHeigth     95

#define kImageWidth        64
#define kImageHeigth       64


@interface TipView ()
{
    UIActivityIndicatorView *_activityIndicator;
    UIImageView             *_imageView;
    UILabel                 *_textLabel;
    UIView                  *_coverView;
    
}

@end

@implementation TipView

DEF_SINGLETON();
@synthesize activityIndicator = _activityIndicator;
@synthesize imageView = _imageView;
@synthesize textLabel = _textLabel;
@synthesize coverView = _coverView;

- (void)dealloc
{

}

- (void)hide
{
    [UIView beginAnimations:@"hide" context:nil];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
    [UIView setAnimationDuration:1.0];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];
    self.alpha = 0.0;
    [UIView commitAnimations];
}

- (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
{
    if ([animationID isEqualToString:@"hide"]) {
        [self removeTipView];
    }
}




- (void)removeTipView
{
    [self removeFromSuperview];
    if (_coverView)
	{
        [_coverView removeFromSuperview];
        _coverView = nil;
	}
}

#pragma
#pragma mark ===================== 扩展  ===================

+ (TipView *)showWaitTipWithTextAndIndicatorNoRespondToTouchByTipView:(NSString *)string
{
    TipView * tipView = [[TipView alloc] initWithTitle:string type:TipType_processing];
    tipView.alpha = 0.0;
    tipView.center = [UIApplication sharedApplication].keyWindow.center;
    [[UIApplication sharedApplication].keyWindow addSubview:tipView];
    
    UIView *temp = [[UIView alloc] initWithFrame:[UIApplication sharedApplication].keyWindow.bounds];
    tipView.coverView = temp;
    tipView.coverView.backgroundColor = [UIColor clearColor];
    tipView.coverView.userInteractionEnabled = YES;
    [[UIApplication sharedApplication].keyWindow addSubview:tipView.coverView];
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
    [UIView setAnimationDuration:0.2];
    tipView.alpha = 1.0;
    [UIView commitAnimations];
	
    return tipView;
}

+(int)calcHorizontalGap:(NSString *)title
{
    int titleCount = [title calculateTextNumber];
    int gap = 0;
    if (titleCount <= 4) {
        gap = 40;
    } else if (4 < titleCount && titleCount <= 6) {
        gap = 40;
    } else if (6 < titleCount && titleCount <= 10) {
        gap = 20;
    } else {
        gap = 25;
    }
    return gap;
}

-(void)resetWithTitle:(NSString *)title type:(TipType)type
{
    int vGapTop = 10;
    int vGapMiddle = 8;
    int hTextGap = [TipView calcHorizontalGap:title]; // need custom
    int vGapBottom = 20;
    int maxWidth = 166;
    int maxHeight = 43;
    
    if (type == TipType_success ||
        type == TipType_fail ||
        type == TipType_alert ||
        type == TipType_processing)
    {
        UIView *iconView = nil;
        
        if (type == TipType_processing) {
            _activityIndicator.hidden = NO;
            iconView = _activityIndicator;
            [_activityIndicator startAnimating];
        } else {
            _activityIndicator.hidden = YES;
            
            _imageView.hidden = NO;
            iconView = _imageView;
        }
        
        NSString *imgName = nil;
        switch (type) {
            case TipType_success:
                imgName = @"toast_success.png";
                break;
            case TipType_fail:
                imgName = @"toast_fail.png";
                break;
            case TipType_alert:
                imgName = @"toast_alert.png";
                break;
            default:
                break;
        }
        
        UIImage *img = [UIImage imageNamed:imgName];
        
        int imgWidth = 40;
        int imgHeight = 40;
        _imageView.image = img;
        
        
        iconView.frame = CGRectMake(0/*will fix at end*/, vGapTop, imgWidth, imgHeight);
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        CGSize size = [title sizeWithFont:_textLabel.font constrainedToSize:CGSizeMake(maxWidth, maxHeight) lineBreakMode:NSLineBreakByWordWrapping];
#pragma clang diagnostic pop

        if ([title calculateTextNumber] > 10)
        {
            _textLabel.numberOfLines = 2;
        }
        else
        {
            _textLabel.numberOfLines = 1;
        }
        _textLabel.text = title;
        _textLabel.frame = CGRectMake(hTextGap, [iconView bottom] + vGapMiddle, MIN(size.width, maxWidth), MIN(maxHeight, size.height));
        
        self.bounds = CGRectMake(0,
								 0,
								 hTextGap*2 + CGRectGetWidth(_textLabel.frame),
								 vGapTop + imgWidth + vGapMiddle + CGRectGetHeight(_textLabel.frame) + vGapBottom);
        
        iconView.frame = CGRectMake(self.frame.size.width/2 - imgWidth/2, vGapTop, imgWidth, imgHeight);
        
    }
    else
    {
        CGSize size = [title sizeWithFont:_textLabel.font constrainedToSize:CGSizeMake(maxWidth, maxHeight) lineBreakMode:NSLineBreakByWordWrapping];
        
        _textLabel.frame = CGRectMake(hTextGap, 40, MIN(size.width, maxWidth), MIN(maxHeight, size.height));
        
        self.bounds = CGRectMake(0,
								 0,
								 hTextGap*2 + CGRectGetWidth(_textLabel.frame),
								 40+_textLabel.frame.size.height+40);
		_textLabel.text = title;

		
    }
    
    _bkgImageView.frame = self.bounds;
	

	
}

- (id)initWithTitle:(NSString *)title type:(TipType)type
{
    self = [super initWithFrame:CGRectMake(0, 0, kTextTipWidth, kTextTipHeigth)];
    if(self)
    {
        _activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        _activityIndicator.hidden = YES;
        _imageView = [[UIImageView alloc] init];
        _imageView.hidden = YES;
        
        UIFont *font = [UIFont systemFontOfSize:16.0];
        _textLabel = [[UILabel alloc] init];
        _textLabel.numberOfLines = 0;
        _textLabel.font = font;
        _textLabel.lineBreakMode = NSLineBreakByWordWrapping;
        _textLabel.backgroundColor = [UIColor clearColor];
        _textLabel.textAlignment = NSTextAlignmentCenter;
        _textLabel.textColor = [UIColor whiteColor];
        [self addSubview:_activityIndicator];
        [self addSubview:_imageView];
        [self addSubview:_textLabel];
        self.backgroundColor = [UIColor clearColor];
        
        _bkgImageView =[[UIImageView alloc] initWithFrame:self.bounds];
        _bkgImageView.image = [[UIImage imageNamed:@"toast.png"] stretchableImageWithLeftCapWidth:4 topCapHeight:4];
        [self insertSubview:_bkgImageView atIndex:0];
        [self resetWithTitle:title type:type];
    }
	
    return self;
	
}

+ (TipView *) showWithTitle:(NSString *)title type:(TipType)type
{
    TipView * tipView = [[TipView alloc] initWithTitle:title type:type];
    
	[TipView removeOtherTipViewFromView:[UIApplication sharedApplication].keyWindow];

    tipView.alpha = 0.0;
    tipView.userInteractionEnabled = NO;
    tipView.center = [UIApplication sharedApplication].keyWindow.center;
    [[UIApplication sharedApplication].keyWindow addSubview:tipView];
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
    [UIView setAnimationDuration:0.2];
    tipView.alpha = 1.0;
    [UIView commitAnimations];
    [tipView performSelector:@selector(hide) withObject:tipView afterDelay:1.5 inModes:@[NSRunLoopCommonModes]];
	
    return tipView;
}


#pragma mark

+ (void)removeOtherTipViewFromView:(UIView*)view
{
    for(UIView* subview in view.subviews)
    {
        if([subview isKindOfClass:[TipView class]])
        {
            TipView* tipView = (TipView*)subview;
            [tipView removeFromSuperview];
        }
    }
}


@end
